package com.camel.base.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.camel.base.config.MyBaseMapper;
import com.camel.core.enums.YesNo;
import com.camel.base.model.ZsSeat;
import com.camel.base.model.ZsSurvey;
import com.camel.base.model.ZsWorkRecord;
import com.camel.base.model.ZsWorkShift;
import com.camel.base.service.ZsSeatService;
import com.camel.base.service.ZsSurveyService;
import com.camel.base.service.ZsWorkRecordService;
import com.camel.base.service.impl.ZsWorkShiftServiceImpl;
import com.camel.core.controller.BaseCommonController;
import com.camel.core.entity.BasePaginationEntity;
import com.camel.core.entity.IFilter;
import com.camel.core.entity.IParams;
import com.camel.core.entity.Result;
import com.camel.core.exceptions.CustomException;
import com.camel.core.service.BaseCommonService;
import com.camel.core.utils.PaginationUtil;
import com.camel.core.utils.ResultUtil;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author camel
 */
@RestController
@RequestMapping("/zsWorkRecord")
public class ZsWorkRecordController extends BaseCommonController<ZsWorkRecord> {

    @Autowired
    private ZsWorkRecordService<ZsWorkRecord> service;

    @Autowired
    private ZsWorkShiftServiceImpl workShiftService;

    @Autowired
    private ZsSurveyService<ZsSurvey> surveyService;

    @Autowired
    private ZsSeatService<ZsSeat> seatService;

    @PostMapping("/me")
    public Result me(@RequestBody IParams params) {

        IParams iParams = new IParams();

        ArrayList<IFilter> filters = new ArrayList<>();
        filters.add(new IFilter("result", "=", "1"));
        filters.add(new IFilter("creator", "=", StpUtil.getLoginIdAsInt()));
        iParams.setFilters(filters);

        List<ZsWorkRecord> list = service.list(iParams);

        List<Integer> shiftIds = list.stream().map(ZsWorkRecord::getShiftId).distinct().collect(Collectors.toList());

        PageInfo<BasePaginationEntity> basePaginationEntityPageInfo = PaginationUtil.startPage(params, () -> {
            MyBaseMapper baseMapper = workShiftService.getBaseMapper();
            if(CollectionUtils.isEmpty(shiftIds)) {
                new ArrayList<>();
            } else {
                baseMapper.selectIndex(new QueryWrapper<ZsWorkShift>().in("id", shiftIds));
            }
        });

        return ResultUtil.success(basePaginationEntityPageInfo);

    }

    @Override
    public Result update(@RequestBody ZsWorkRecord entity) {
        Result update = super.update(entity);
        if (update.isSuccess() && entity.getResult() == 1) {
            Integer shiftId = entity.getShiftId();
            // 查询出班次
            ZsWorkShift shift = workShiftService.getById(shiftId);

            if (ObjectUtils.isEmpty(shift)) {
                throw new CustomException("无效的申请: 班次不存在");
            }
            // 查询班次对应使用队列下班次申请人使用的坐席
            List<ZsSeat> usedSeat = seatService.list(new QueryWrapper<ZsSeat>()
                    .eq("queue_id", shift.getQueueId())
                    .eq("state", YesNo.YES.getValue())
                    .eq("uid", entity.getCreator()));
            if(!CollectionUtils.isEmpty(usedSeat)) {
                return update;
            }

            // 查询班次对应使用队列下的空闲坐席
            List<ZsSeat> freeSeats = seatService.list(new QueryWrapper<ZsSeat>()
                    .eq("queue_id", shift.getQueueId())
                    .eq("state", YesNo.NO.getValue()));
            if (CollectionUtils.isEmpty(freeSeats)) {
                update.setMsg("审核通过，但坐席队列中已无可分配空闲坐席。");
                return update;
            }
            // 随便取出一个空闲坐席
            ZsSeat zsSeat = freeSeats.get(0);
            // 设置这个坐席临时的 使用人| 工号 | 即将要参与的问卷ID
            zsSeat.setUid(entity.getCreator());
            zsSeat.setState(YesNo.YES);
            zsSeat.setWorkNum(new DecimalFormat("P000000").format(entity.getCreator()));
            zsSeat.setSurveyId(shift.getSurveyId());
        }
        return update;
    }

    /**
     * 验证我是否能开始某个问卷的调查
     *
     * @param id
     * @return
     */
    @GetMapping("/valid/{id}")
    private Result validIStart(@PathVariable Integer id) throws ParseException {
        // 今日日期
        String format = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        Date startDate = DateUtils.parseDate(format + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
        Date endDate = DateUtils.parseDate(format + " 23:59:59", "yyyy-MM-dd HH:mm:ss");

        // 今天的班次
        List<ZsWorkShift> workShifts = workShiftService.list(new QueryWrapper<ZsWorkShift>()
                .eq("survey_id", id)
                .ge("shift_date", startDate)
                .lt("shift_date", endDate));
        if (CollectionUtils.isEmpty(workShifts)) {
            return ResultUtil.error("当前无班次,请关注首页班次信息申请后再试");
        }
        Date n = new Date();
        for (ZsWorkShift workShift : workShifts) {
            String startTimeStr = format + " " + workShift.getStartTime();
            String endTimeStr = format + " " + workShift.getEndTime();
            try {
                Date startTime = DateUtils.parseDate(startTimeStr, "yyyy-MM-dd HH:mm");
                Date endTime = DateUtils.parseDate(endTimeStr, "yyyy-MM-dd HH:mm");
                if (n.getTime() > startTime.getTime() && n.getTime() < endTime.getTime()) {
                    return ResultUtil.success("您已经申请并通过班次了");
                } else {
                    continue;
                }
            } catch (ParseException e) {
                System.err.println(e.getMessage());
                // 数据库班次数据异常
                continue;
            }
        }
        return ResultUtil.error("当前无班次,请关注首页班次信息申请后再试");
    }

    @Override
    public boolean deleteAble(Serializable id) {
        ZsWorkRecord byId = service.getById(id);
        if (ObjectUtils.isEmpty(byId)) {
            throw new CustomException("删除失败: " + getMouduleName() + "不存在");
        }
        return true;
    }

    @Override
    public BaseCommonService<ZsWorkRecord> getiService() {
        return service;
    }

    @Override
    public String getMouduleName() {
        return "班次报名";
    }
}
